/**
 * @author hugh
 * @time  2021-01-10 11:40
 * @title  工具类
 * @desc
 *
 */
import {
  ElMessage,
  ElMessageBox
} from 'element-plus';
export const parseTime = (
  time?: object | string | number | null,
  cFormat?: string
): string | null => {
  if (time === undefined || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date: Date
  if (typeof time === 'object') {
    date = time as Date
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj: { [key: string]: number } = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}

// Format and filter json data using filterKeys array
export const formatJson = (filterKeys: any, jsonData: any) =>
  jsonData.map((data: any) => filterKeys.map((key: string) => {
    if (key === 'timestamp') {
      return parseTime(data[key])
    } else {
      return data[key]
    }
  }))

// Check if an element has a class
export const hasClass = (ele: HTMLElement, className: string) => {
  return !!ele.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}

// Add class to element
export const addClass = (ele: HTMLElement, className: string) => {
  if (!hasClass(ele, className)) ele.className += ' ' + className
}

// Remove class from element
export const removeClass = (ele: HTMLElement, className: string) => {
  if (hasClass(ele, className)) {
    const reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

// Toggle class for the selected element
export const toggleClass = (ele: HTMLElement, className: string) => {
  if (!ele || !className) {
    return
  }
  let classString = ele.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  ele.className = classString
}
export const showDialog = (msg: string) => {
  return ElMessageBox.confirm(msg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  });
}
export const showMsg = (msg: string, status: number) => {
  if (status === 1) {
    return ElMessage.success({
      message: msg,
      type: 'success'
    });
  } else {
    return ElMessage.warning({
      message: msg,
      type: 'warning'
    });
  }
}
/**
      * 获取树型结构格式化
      */
export const getTreeList = (tableData: any, type: string) => {
  let checks = [];
  let ids = [];
  for (let i = 0; i < tableData.length; i++) {
    if (tableData[i].checked) {
      checks.push(tableData[i][type]);
    }
    ids.push(tableData[i][type]);
    tableData[i]['id'] = i + 1;
    let j_length = tableData[i].childs.length;
    if (j_length > 0) {
      for (let j = 0; j < j_length; j++) {
        if (tableData[i].childs[j].checked) {
          checks.push(tableData[i].childs[j][type]);
        }
        ids.push(tableData[i].childs[j][type]);
        tableData[i].childs[j]['id'] = (i + 1) * 10 + j;
        let k_length = tableData[i].childs[j].childs.length;
        if (k_length > 0) {
          for (let k = 0; k < k_length; k++) {
            if (tableData[i].childs[j].childs[k].checked) {
              checks.push(tableData[i].childs[j].childs[k][type]);
            }
            ids.push(tableData[i].childs[j].childs[k][type]);
            tableData[i].childs[j].childs[k]['id'] = (i + 1) * 100 + (j + 1) * 10 + k;
          }
        }
      }
    }
  }
  return {
    checks,
    tableData,
    ids
  };
}
/**
      * 获取树型结构格式化
      */
export const setTreeList = (tableData: any) => {
  for (let i = 0; i < tableData.length; i++) {
    tableData[i]['id'] = i+'';
    if (tableData[i].childs && tableData[i].childs.length > 0) {
      for (let j = 0, j_length = tableData[i].childs.length; j < j_length; j++) {
        tableData[i].childs[j]['id'] = tableData[i]['id'] + '_' + j;
        if (tableData[i].childs[j].childs && tableData[i].childs[j].childs.length > 0) {
          for (let k = 0, k_length = tableData[i].childs[j].childs.length; k < k_length; k++) {
            tableData[i].childs[j].childs[k]['id'] = tableData[i].childs[j]['id'] + '_' + k;
          }
        }
      }
    }
  }
  return tableData;
}
/**
      * 获取级联结构格式化
      */
export const getCascader = (tableData: any, key: string, value: string) => {
  let checks: number[] = [];
  let lists: any[] = [];
  if (tableData.length <= 0) {
    return {
      checks,
      lists
    };
  }
  for (let i = 0; i < tableData.length; i++) {
    lists[i] = {
      value: tableData[i][key],
      label: tableData[i].name,
      children: []
    }
    if (tableData[i][key] === value) {
      checks.push(tableData[i][key]);
    }
    let j_length = tableData[i].childs.length;
    if (j_length > 0) {
      for (let j = 0; j < j_length; j++) {
        lists[i].children[j] = {
          value: tableData[i].childs[j][key],
          label: tableData[i].childs[j].name,
          children: []
        }
        if (tableData[i].childs[j][key] === value) {
          checks.push(tableData[i][key]);
          checks.push(tableData[i].childs[j][key]);
        }
        let k_length = tableData[i].childs[j].childs.length;
        if (k_length > 0) {
          for (let k = 0; k < k_length; k++) {
            lists[i].children[j].children[k] = {
              value: tableData[i].childs[j].childs[k][key],
              label: tableData[i].childs[j].childs[k].name
            }
            if (tableData[i].childs[j].childs[k][key] === value) {
              checks.push(tableData[i][key]);
              checks.push(tableData[i].childs[j][key]);
              checks.push(tableData[i].childs[j].childs[k][key]);
            }
          }
        }
      }
    }
  }
  return {
    checks,
    lists
  };
}
/**
* 查找选中级联对象值
*/
export const getTreeCheck = (tableData: any, key: string, value: string) => {
  let checks: any[] = [];
  for (let i = 0; i < tableData.length; i++) {
    if (tableData[i][key] === value) {
      checks[0] = tableData[i].name;
    }
    for (let j = 0, j_length = tableData[i].childs.length; j < j_length; j++) {
      if (tableData[i].childs[j][key] === value) {
        checks[1] = tableData[i].childs[j].name;
      }
      for (let k = 0, k_length = tableData[i].childs[j].childs.length; k < k_length; k++) {
        if (tableData[i].childs[j].childs[k][key] === value) {
          checks[2] = tableData[i].childs[j].childs[k].name;
        }
      }
    }
  }
  return checks;
}
export const subArray = (arr1: any, arr2: any) => {
  var set2 = new Set(arr2);
  var subset: any[] = [];
  arr1.forEach(function (val: any, index: number) {
    if (!set2.has(val)) {
      subset.push(val);
    }
  });
  return subset;
};

export const randomString = (len: number) => {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}
export const getQueryVariable = (variable: any) => {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}
